{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6488fdaf",
   "metadata": {},
   "source": [
    "# Chat Prompt Templates\n",
    "\n",
    "[Chat Models](../models/chat.rst) take a list of `chat messages as` input - this list commonly referred to as a `prompt`.\n",
    "These chat messages differ from raw string (which you would pass into a [LLM](../models/llms.rst) model) in that every message is associated with a `role`.\n",
    "\n",
    "For example, in OpenAI [Chat Completion API](https://platform.openai.com/docs/guides/chat/introduction), a chat message can be associated with the AI, human or system role. The model is supposed to follow instruction from system chat message more closely.\n",
    "\n",
    "LangChain provides several prompt templates to make constructing and working with prompts easily. You are encouraged to use these chat related prompt templates instead of `PromptTemplate` when querying chat models to fully exploit the potential of underlying chat model.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "7647a621",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.prompts import (\n",
    "    ChatPromptTemplate,\n",
    "    PromptTemplate,\n",
    "    SystemMessagePromptTemplate,\n",
    "    AIMessagePromptTemplate,\n",
    "    HumanMessagePromptTemplate,\n",
    ")\n",
    "from langchain.schema import (\n",
    "    AIMessage,\n",
    "    HumanMessage,\n",
    "    SystemMessage\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "acb4a2f6",
   "metadata": {},
   "source": [
    "To create a message template associated with a role, you use `MessagePromptTemplate`. \n",
    "\n",
    "For convenience, there is a `from_template` method exposed on the template. If you were to use this template, this is what it would look like:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "3124f5e9",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "template=\"You are a helpful assistant that translates {input_language} to {output_language}.\"\n",
    "system_message_prompt = SystemMessagePromptTemplate.from_template(template)\n",
    "human_template=\"{text}\"\n",
    "human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c8b08cda-7c57-4c15-a1e5-80627cfa9cbd",
   "metadata": {},
   "source": [
    "If you wanted to construct the `MessagePromptTemplate` more directly, you could create a PromptTemplate outside and then pass it in, eg:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "5a8d249e",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "prompt=PromptTemplate(\n",
    "    template=\"You are a helpful assistant that translates {input_language} to {output_language}.\",\n",
    "    input_variables=[\"input_language\", \"output_language\"],\n",
    ")\n",
    "system_message_prompt_2 = SystemMessagePromptTemplate(prompt=prompt)\n",
    "\n",
    "assert system_message_prompt == system_message_prompt_2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96836c5c-41f8-4073-95ac-ea1daab2e00e",
   "metadata": {},
   "source": [
    "After that, you can build a `ChatPromptTemplate` from one or more `MessagePromptTemplates`. You can use `ChatPromptTemplate`'s `format_prompt` -- this returns a `PromptValue`, which you can convert to a string or Message object, depending on whether you want to use the formatted value as input to an llm or chat model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "9c7e2e6f",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}),\n",
       " HumanMessage(content='I love programming.', additional_kwargs={})]"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])\n",
    "\n",
    "# get a chat completion from the formatted messages\n",
    "chat_prompt.format_prompt(input_language=\"English\", output_language=\"French\", text=\"I love programming.\").to_messages()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0899f681-012e-4687-a754-199a9a396738",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Format output\n",
    "\n",
    "The output of the format method is available as string, list of messages and `ChatPromptValue`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "584166de-0c31-4bc9-bf7a-5b359e7173d8",
   "metadata": {},
   "source": [
    "As string:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "2f6c7ad1-def5-41dc-a4fe-3731dc8917f9",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'System: You are a helpful assistant that translates English to French.\\nHuman: I love programming.'"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "output = chat_prompt.format(input_language=\"English\", output_language=\"French\", text=\"I love programming.\")\n",
    "output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "144b3368-43f3-49fa-885f-3f3470e9ab7e",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# or alternatively \n",
    "output_2 = chat_prompt.format_prompt(input_language=\"English\", output_language=\"French\", text=\"I love programming.\").to_string()\n",
    "\n",
    "assert output == output_2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "51970399-c2e1-4c9b-8003-6f5b1236fda8",
   "metadata": {},
   "source": [
    "As `ChatPromptValue`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "681ce4a7-d972-4cdf-ac77-ec35182fd352",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ChatPromptValue(messages=[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}), HumanMessage(content='I love programming.', additional_kwargs={})])"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chat_prompt.format_prompt(input_language=\"English\", output_language=\"French\", text=\"I love programming.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61041810-4418-4406-9c8a-91c9034c9752",
   "metadata": {},
   "source": [
    "As list of Message objects"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "4ec2f166-1ef9-4071-8c37-fcfbd3f4bc29",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}),\n",
       " HumanMessage(content='I love programming.', additional_kwargs={})]"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chat_prompt.format_prompt(input_language=\"English\", output_language=\"French\", text=\"I love programming.\").to_messages()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73dcd3a2-ad6d-4b7b-ab21-1d9e417f959e",
   "metadata": {},
   "source": [
    "## Different types of `MessagePromptTemplate`\n",
    "\n",
    "LangChain provides different types of `MessagePromptTemplate`. The most commonly used are `AIMessagePromptTemplate`, `SystemMessagePromptTemplate` and `HumanMessagePromptTemplate`, which create an AI message, system message and human message respectively.\n",
    "\n",
    "However, in cases where the chat model supports taking chat message with arbitrary role, you can use `ChatMessagePromptTemplate`, which allows user to specify the role name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "55a21b1f-9cdc-4072-a41d-695b00dd11e6",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ChatMessage(content='May the force be with you', additional_kwargs={}, role='Jedi')"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.prompts import ChatMessagePromptTemplate\n",
    "\n",
    "prompt = \"May the {subject} be with you\"\n",
    "\n",
    "chat_message_prompt = ChatMessagePromptTemplate.from_template(role=\"Jedi\", template=prompt)\n",
    "chat_message_prompt.format(subject=\"force\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cd6bf82b-4709-4683-b215-6b7c468f3347",
   "metadata": {},
   "source": [
    "LangChain also provides `MessagesPlaceholder`, which gives you full control of what messages to be rendered during formatting. This can be useful when you are uncertain of what role you should be using for your message prompt templates or when you wish to insert a list of messages during formatting."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "9f034650-5e50-4bc3-80f8-5e428ca6444d",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.prompts import MessagesPlaceholder\n",
    "\n",
    "human_prompt = \"Summarize our conversation so far in {word_count} words.\"\n",
    "human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)\n",
    "\n",
    "chat_prompt = ChatPromptTemplate.from_messages([MessagesPlaceholder(variable_name=\"conversation\"), human_message_template])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "9789e8e7-b3f9-4391-a85c-373e576107b3",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[HumanMessage(content='What is the best way to learn programming?', additional_kwargs={}),\n",
       " AIMessage(content='1. Choose a programming language: Decide on a programming language that you want to learn. \\n\\n2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.\\n\\n3. Practice, practice, practice: The best way to learn programming is through hands-on experience', additional_kwargs={}),\n",
       " HumanMessage(content='Summarize our conversation so far in 10 words.', additional_kwargs={})]"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "human_message = HumanMessage(content=\"What is the best way to learn programming?\")\n",
    "ai_message = AIMessage(content=\"\"\"\\\n",
    "1. Choose a programming language: Decide on a programming language that you want to learn. \n",
    "\n",
    "2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.\n",
    "\n",
    "3. Practice, practice, practice: The best way to learn programming is through hands-on experience\\\n",
    "\"\"\")\n",
    "\n",
    "chat_prompt.format_prompt(conversation=[human_message, ai_message], word_count=\"10\").to_messages()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
